//
//  AppDelegate.m
//  HybridBridge
//
//  Created by 文道江 on 15/11/20.
//  Copyright © 2015年 文道江. All rights reserved.
//

#import <PushKit/PushKit.h>
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
#import "ViewController.h"
#import "PlayVibrate.h"

@interface AppDelegate () <PKPushRegistryDelegate>

@property UILocalNotification *backgroudMsg;
@property PKPushRegistry *voipRegistry;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    ViewController *vc = [[ViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
    [self registerVoipNotifications];
    NSLog(@"___________didFinishLaunchingWithOptions");
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [self stopNotify];
    [super application:application didReceiveLocalNotification:notification];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [super applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    [super applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [self stopNotify];
    [super applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [super applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [super applicationWillTerminate:application];
}


-(void)registerVoipNotifications{
    _voipRegistry = [[PKPushRegistry alloc]initWithQueue: dispatch_get_main_queue()];
    _voipRegistry.delegate = self;
    _voipRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
    UIUserNotificationType types = (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert);
    UIUserNotificationSettings * notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication]registerUserNotificationSettings:notificationSettings];
    NSLog(@"app launched with state %d", [UIApplication sharedApplication].applicationState);
}

/*
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type {
    NSString *str = [NSString stringWithFormat:@"%@",credentials.token];
    NSString *_tokenStr = [[[str stringByReplacingOccurrencesOfString:@"<" withString:@""]
            stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [KVStorage setKey:@"push_registry_credentials" Value:_tokenStr];
    NSLog(@"device_token is %@" , _tokenStr);
}

- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type {
    NSLog(@"device_token fail %@" , type);
}*/

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    NSLog(@"didRegisterUserNotificationSettings called");
}

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type {
    NSString *str = [NSString stringWithFormat:@"%@", credentials.token];
    NSString *_tokenStr = [[[str stringByReplacingOccurrencesOfString:@"<" withString:@""]
            stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [KVStorage setKey:@"push_registry_credentials" Value:_tokenStr];
    NSLog(@"device_token is %@", _tokenStr);
}

- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(NSString *)type {
    NSLog(@"device_token fail %@" , type);
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type{

    NSLog(@"incoming notificaiton from background");

    UIUserNotificationType theType = [UIApplication sharedApplication].currentUserNotificationSettings.types;

    if (theType == UIUserNotificationTypeNone)
    {
        UIUserNotificationSettings *userNotifySetting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:userNotifySetting];
    }

    NSDictionary * dic = payload.dictionaryPayload;

    NSLog(@"dic  %@",dic);

    NSDictionary *alert = dic[@"alert"];
    if(alert == nil){
        alert = @{
                @"body": @"你收到一个新的电话",
                @"action": @"接听",
                @"sound": @"call_ring.mp3",
                @"badge": @(1),
        };
    }

    if ([dic[@"cmd"] isEqualToString:@"call"]) {
        _backgroudMsg = [[UILocalNotification alloc] init];
        _backgroudMsg.alertBody = alert[@"body"];
        _backgroudMsg.soundName = alert[@"sound"];
        _backgroudMsg.alertAction = alert[@"action"];
        _backgroudMsg.applicationIconBadgeNumber = [alert[@"badge"] integerValue];
        [[PlayVibrate shareInstance] playVibrate];
        [[UIApplication sharedApplication] presentLocalNotificationNow:_backgroudMsg];

        [self performSelector:@selector(stopNotify) withObject:nil afterDelay: 20];
    }else if([dic[@"cmd"] isEqualToString:@"cancel"]){
        [self stopNotify];
        UILocalNotification * wei = [[UILocalNotification alloc] init];
        wei.alertBody= [NSString stringWithFormat:@"%i 个未接来电", [[UIApplication sharedApplication]applicationIconBadgeNumber]];
        wei.applicationIconBadgeNumber = [[UIApplication sharedApplication]applicationIconBadgeNumber];
        [[UIApplication sharedApplication] presentLocalNotificationNow:wei];
    }

}

- (void) stopNotify {
    if(_backgroudMsg != nil){
        [[UIApplication sharedApplication] cancelLocalNotification:_backgroudMsg];
        _backgroudMsg = nil;
    }
    [[PlayVibrate shareInstance] stopPlayVibrate];
    NSLog(@"stopNotify");
}


@end
